<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="请输入SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option :label="tm.tmName" :value="tm.id" v-for="tm in tmList" :key="tm.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input type="textarea" rows="4" placeholder="描述" v-model="spu.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <!-- 
              action 图片上传地址
              :file-list 展示所需的数据
        -->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unselectedAttr.length}未选择`" v-model="unselectAttrId">
          <el-option
            :label="unselect.name"
            :value="`${unselect.id}:${unselect.name}`"
            v-for="unselect in unselectedAttr"
            :key="unselect.id"
          ></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" style="margin:0 10px" :disabled="!unselectAttrId" @click="addSaleAttr">添加销售属性</el-button>
        <el-table border style="width: 100%;margin: 20px 0;" :data="spu.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80px" align="center"></el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width"></el-table-column>
          <el-table-column prop="prop" label="属性值名列表" width="width">
            <template slot-scope="{row,$index}">
              <!-- tag -->
              <el-tag
                :key="tag.id"
                v-for="(tag,index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index,1)"
              >{{tag.saleAttrValueName}}</el-tag>
              <!-- input -->
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @blur="handleInputConfirm(row)"
                @keyup.enter.native="handleInputConfirm(row)"
              ></el-input>
              <el-button v-else class="button-new-tag" size="small" @click="addAttrValue(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{row,$index}">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="spu.spuSaleAttrList.splice($index,1)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="$emit('changeScene',{scene:0,flag:''})">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'SpuForm',
  data() {
    return {
      // 照片墙相关属性
      dialogImageUrl: '',
      dialogVisible: false,
      // 接收服务器传来的数据
      // spu信息
      spu: {
        //三级分类id
        category3Id: 0,
        description: '',
        // 图片信息
        spuImageList: [
          {
            id: 0,
            imgName: 'string',
            imgUrl: 'string',
            spuId: 0
          }
        ],
        spuName: '',
        spuSaleAttrList: [
          {
            baseSaleAttrId: 0,
            id: 0,
            saleAttrName: 'string',
            spuId: 0,
            spuSaleAttrValueList: [
              {
                baseSaleAttrId: 0,
                id: 0,
                isChecked: 'string',
                saleAttrName: 'string',
                saleAttrValueName: 'string',
                spuId: 0
              }
            ]
          }
        ],
        // 品牌id
        tmId: ''
      },
      tmList: [], // 品牌信息
      spuImageList: [], // spu图片
      saleAttrList: [], // 销售属性
      unselectAttrId: '' // 尚未选择的属性id
    }
  },
  methods: {
    // 照片墙相关方法
    handleRemove(file, fileList) {
      console.log(file, fileList)
      // 需要收集删除后，剩余图片的数据
      this.spuImageList = fileList
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess(response, file, fileList) {
      // 上传成功后，收集照片墙数据信息
      this.spuImageList = fileList
    },
    // 初始化Spu表单
    async initSpuFormData(spu) {
      // 获取spu信息
      const spuResult = await this.$API.spu.reqSpuInfo(spu.id)
      if (spuResult.code === 200) {
        // console.log(spuResult)
        this.spu = spuResult.data
      }
      // 获取品牌信息
      const tmResult = await this.$API.spu.reqTradeMarkList()
      if (tmResult.code === 200) {
        // console.log(tmResult)
        this.tmList = tmResult.data
      }
      // 获取spu图片
      const spuImageResult = await this.$API.spu.reqSpuImage(spu.id)
      if (spuImageResult.code === 200) {
        // console.log(spuImageResult)
        const arrList = spuImageResult.data
        // 为能够正常使用 ele ui，需要为对象添加 name，url两个属性
        arrList.forEach(item => {
          item.name = item.imgName
          item.url = item.imgUrl
        })
        this.spuImageList = arrList
      }
      // 获取销售属性
      const saleAttrResult = await this.$API.spu.reqBaseSaleAttrList()
      if (saleAttrResult.code === 200) {
        // console.log(saleAttrResult)
        this.saleAttrList = saleAttrResult.data
      }
    },
    // 添加销售属性
    addSaleAttr() {
      // 把收集到的 unselectAttrId 进行处理
      const [baseSaleAttrId, saleAttrName] = this.unselectAttrId.split(':')
      // 向 spu.spuSaleAttrList 添加新属性，注意新对象的结构和属性名要一致
      const newAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] }
      this.spu.spuSaleAttrList.push(newAttr)
      this.unselectAttrId = ''
    },
    // tag/input组件相关方法
    // 点击添加tag按钮的回调
    addAttrValue(row) {
      // 添加响应式属性 row.inputVisible
      this.$set(row, 'inputVisible', 'true')
      this.$set(row, 'inputValue', '')
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    // input失焦，回车时，确认添加属性值
    handleInputConfirm(row) {
      // 解构 row
      const { baseSaleAttrId, inputValue } = row
      // 判断 inputValue 的值是否合礼法
      if (inputValue.trim() == '') {
        this.$message('输入不能为空')
        return false
      }
      const isRepeat = row.spuSaleAttrValueList.some(item => item.saleAttrValueName == inputValue)
      if (isRepeat) {
        this.$message('输入重复')
        return false
      }
      const newAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue }
      row.spuSaleAttrValueList.push(newAttrValue)
      row.inputVisible = false
    },
    // 保存修改、添加的spu
    async addOrUpdateSpu() {
      // 整理参数，照片墙数据里，要新增 imgName,imgUrl,传进去 data里的 spu中
      this.spu.spuImageList = this.spuImageList.map(item => {
        return {
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url
        }
      })
      // spu中其他属性已准备完毕，向服务器发送请求
      const result = await this.$API.spu.reqAddOrUpdateSpu(this.spu)
      if (result.code === 200) {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
        this.$emit('changeScene', { scene: 0, flag: this.spu.id ? '修改' : '添加' })
      }
    },
    // 点击添加spu按钮后，父组件要调用的函数
    async addSpuData(c3Id) {
      //   清空上次残留的数据
      //  Object.assign 合并对象，  this.$options.data() 即原本的 data()返回的对象
      Object.assign(this._data, this.$options.data())
      this.spu.spuSaleAttrList = []
      this.spu.category3Id = c3Id
      // 获取品牌信息
      const tmResult = await this.$API.spu.reqTradeMarkList()
      if (tmResult.code === 200) {
        // console.log(tmResult)
        this.tmList = tmResult.data
      }
      // 获取销售属性
      const saleAttrResult = await this.$API.spu.reqBaseSaleAttrList()
      if (saleAttrResult.code === 200) {
        // console.log(saleAttrResult)
        this.saleAttrList = saleAttrResult.data
      }
    }
  },
  computed: {
    // 计算出还没选择的属性
    unselectedAttr() {
      //平台所有的属性 --- saleAttrList
      // 当前spu所有的属性 --- spu.spuSaleAttrList
      let arr = this.saleAttrList.filter(item => {
        return this.spu.spuSaleAttrList.every(item1 => {
          return item.name != item1.saleAttrName
        })
      })
      return arr
    }
  }
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>